package com.funcourse.demo;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.funcourse.demo.wechat.client.WechatJacksonMessageConverter;
import java.util.List;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.lang.Nullable;
import org.springframework.scheduling.TaskScheduler;
import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler;
import org.springframework.web.client.RestTemplate;

@Configuration
public class SpringConfig {

  @Bean
  public RestTemplate restTemplate(){
    RestTemplate restTemplate = new RestTemplate();
    List<HttpMessageConverter<?>> messageConverters = restTemplate.getMessageConverters();
    WechatJacksonMessageConverter wechatJacksonMessageConverter = new WechatJacksonMessageConverter(new ObjectMapper());
    for(int i =0;i<messageConverters.size();i++){
      if(messageConverters.get(i) instanceof MappingJackson2HttpMessageConverter){
        messageConverters.remove(i);
        break;
      }
    }
    messageConverters.add(wechatJacksonMessageConverter);
    return  restTemplate;
  }

  @Bean
  public ObjectMapper objectMapper(){
    return new ObjectMapper();
  }

  /**
   * websocket conflict with EnableScheduling, use this bean to solve
   * Bean named 'defaultSockJsTaskScheduler' is expected to be of type 'org.springframework.scheduling.TaskScheduler' but was actually of type 'org.springframework.beans.factory.support.NullBean'
   * @return
   */
  @Bean
  @Nullable
  public TaskScheduler taskScheduler() {
    ThreadPoolTaskScheduler threadPoolScheduler = new ThreadPoolTaskScheduler();
    threadPoolScheduler.setThreadNamePrefix("SockJS-");
    threadPoolScheduler.setPoolSize(Runtime.getRuntime().availableProcessors());
    threadPoolScheduler.setRemoveOnCancelPolicy(true);
    return threadPoolScheduler;
  }

}
